// mkdirSync 同步创建目录   默认创建目录必须父级存在 才能创建子目录
// 
let fs = require('fs')
let path = require('path')
// 同步递归创建目录
function mkdirSync(paths) {
  let arr = paths.split('/')
  // let path = ''
  for(let i = 0; i<arr.length; i++) {
    // let item = arr[i]
    // path += item+'/'
    let path = arr.slice(0, i+1).join('/') // 思路要变下
    path.slice(0, -1)
    try {
      fs.accessSync(path)
    } catch (error) {
      fs.mkdirSync(path)
    }
  }
}

// mkdirSync('a/b/c')

// 异步创建目录
function mkdir(paths, cb) {
  let arr = paths.split('/')
  function next(index) {
    if(index > arr.length) return cb()
    let path = arr.slice(0, index).join('/')
    fs.access(path,(err)=> {
      if(err) {  // 不存在的话  就创建
        fs.mkdir(path, ()=>next(index+1))
      }else{
        next(index+1)
      }
    })
  }
  next(1)
}
// mkdir('a/b/c', ()=>{console.log('创建成功')})

// 删除目录  rmdir
// 删除文件  unlink
// fs.stat 文件的状态  statObj.isDirectory() 是否是目录
// 读取目录 fs.readdir

// 先序深度 遍历 
function removeDirSync(dir) {
  let obj = fs.statSync(dir)
  if(obj.isDirectory()){
    let dirs = fs.readdirSync(dir)
    for(let i=0;i<dirs.length;i++){
      let current = path.join(dir, dirs[i])
      removeDirSync(current)
    }
    // 删除完子节点在把自己删除
    fs.rmdirSync(dir)
  }else{
    fs.unlinkSync(dir)
  }
}
// removeDirSync('a')

// 广度遍历
function weak(dir) {
  let arr = [dir] 
  let index = 0
  while(current = arr[index++]) {
    let obj = fs.statSync(current)
    if(obj.isDirectory()) {
      let dirs =  fs.readdirSync(current)   
      dirs = dirs.map(item => path.join(current, item))
      arr = [...arr, ...dirs]
    }
  }
  console.log(arr)
  while(current = arr.pop()){
    let statObj = fs.statSync(current)
    if(statObj.isDirectory()) {
      fs.rmdirSync(current)
    }else{
      fs.unlinkSync(current)
    }
  }
}
// weak('a')

// 异步串行
function rmdirSeries(dir, callback) {
  fs.stat(dir, (err, statObj) => {
    if(statObj.isDirectory()) {
      fs.readdir(dir, (err, dirs) => {
        dirs = dirs.map(d => path.join(dir, d))
        function next(index) {
          if(index === dirs.length) return fs.rmdir(dir, callback)
          rmdirSeries(dirs[index], () => next(index+1))
        }
        next(0)
      })
    }else{
      fs.unlink(dir, callback)
    }
  })
}

// rmdirSeries('a', () =>{
//   console.log('删除成功')
// })

// 异步并发删除
function rmdirParalle(dir, callback) {
  fs.stat(dir, (err, statObj) => {
    if(statObj.isDirectory()) {
      fs.readdir(dir, (err, dirs) => {
        if(dirs.length == 0) {
          return fs.rmdir(dir, callback)
        }
        let index = 0
        function done() {
          if(++index == dirs.length) {
            fs.rmdir(dir, callback)
          }
        } 
        dirs.map(d => {
          let current = path.join(dir, d)
          rmdirParalle(current, done)
        })
      })
    }else{
      fs.unlink(dir, callback)
    }
  })
}
rmdirParalle('a', ()=>{console.log('删除成个')})